// Package model
// @Author zhongxc
// @Date 2024/7/3 10:57:00
// @Desc
package model

import (
	"gorm.io/gorm"
	"log"
	"time"
)

type DepartmentModel struct {
	Id        int64     `gorm:"column:id;primary_key" json:"id"`
	ParentId  int64     `gorm:"column:parent_id" json:"parent_id"`
	Name      string    `gorm:"column:name" json:"name"`
	SortNo    int64     `gorm:"column:sort_no" json:"sort_no"`
	Status    int8      `gorm:"column:status" json:"status"`
	Remark    string    `gorm:"column:remark" json:"remark"`
	Deleted   int8      `gorm:"column:deleted" json:"deleted"`
	DeletedAt time.Time `gorm:"column:deleted_at" json:"deleted_at"`
	CreatedBy string    `gorm:"column:created_by" json:"created_by"`
	CreatedAt time.Time `gorm:"column:created_at" json:"created_at"`
	UpdatedBy string    `gorm:"column:updated_by" json:"updated_by"`
	UpdatedAt time.Time `gorm:"column:updated_at" json:"updated_at"`
}

func (d *DepartmentModel) TableName() string {
	return "sys_department"
}

func NewDepartmentModel() *DepartmentModel {
	return &DepartmentModel{}
}

// const (
// 	IgnoreDeletedAt = "DeletedAt"
// 	IgnoreUpdatedBy = "UpdatedBy"
// 	IgnoreUpdatedAt = "UpdatedAt"
// 	IgnoreCreatedAt = "CreatedAt"
// 	IgnoreCreatedBy = "CreatedBy"
// )

// BeforeCreate 是 GORM 提供的钩子函数，用于在记录插入数据库之前执行操作
func (d *DepartmentModel) BeforeCreate(tx *gorm.DB) (err error) {
	// 例如，初始化时间字段
	d.CreatedAt = time.Now()
	log.Printf("BeforeCreate: %+v", d.CreatedAt)
	return
}

// BeforeUpdate 是 GORM 提供的钩子函数，用于在记录更新数据库之前执行操作
func (d *DepartmentModel) BeforeUpdate(tx *gorm.DB) (err error) {
	// 例如，更新时间戳
	d.UpdatedAt = time.Now()
	return
}

// SoftDelete 是一个示例函数，模拟软删除
// 注意：实际中应根据业务逻辑调整，确保DeletedAt非空时逻辑删除生效
func (d *DepartmentModel) SoftDelete() error {
	// 假设当前时间为删除时间
	d.DeletedAt = time.Now()
	d.Deleted = 1 // 标记为已删除
	log.Printf("SoftDelete: %+v", d.DeletedAt)
	// 更新数据库记录
	// err := db.Model(d).Update("deleted_at", d.DeletedAt).Update("deleted", d.Deleted).Error
	// return err
	return nil
}
